from django.shortcuts import render
from cart.models import CartModel
from cart.cartser import CartSerializer
from rest_framework.views import APIView
from rest_framework.response import Response
from django.db.models import Q


# Create your views here.
class AddCartView(APIView):
    def post(self, request):
        user = request.data.get('user')
        cname = request.data.get('cname')
        num = request.data.get('num')
        weight = request.data.get('weight')
        price = request.data.get('price')
        print(user)
        cart = CartModel.objects.filter(cname=cname,user=user).first()
        if cart:
            cart.num += 1
            cart.save()
            return Response({"message":"数量已+1"})
        else:
            adddata = {
                'user':user,
                'cname':cname,
                'num':num,
                'pound':weight,
                'price':price,
            }
            serializer = CartSerializer(data=adddata)
            if serializer.is_valid():
                serializer.save()
            return Response({"message":"添加成功",'data':serializer.data,'code':200})
class CartList(APIView):
    def get(self, request):
        user = request.GET.get('user')
        carts = CartModel.objects.filter(user_id=user)
        serializer = CartSerializer(carts, many=True)
        return Response(serializer.data)
class AddNumView(APIView):
    def put(self, request):
        id = request.data.get('id')
        cart = CartModel.objects.filter(id=id).first()
        cart.num += 1
        cart.save()
        return Response({"message":"修改成功"})
class NumCartView(APIView):
    def put(self, request):
        id = request.data.get('id')
        cart = CartModel.objects.filter(id=id).first()
        if cart.num == 0:
            cart.delete()
            return Response({"message":"删除成功",'code':400})
        else:
            cart.num -= 1
            cart.save()
            return Response({"message":"修改成功"})
class SelectCartView(APIView):
    def put(self, request):
        id = request.data.get('id')
        info = CartModel.objects.filter(id=id).first()
        info.select = not info.select
        info.save()
        return Response({"message":"修改成功"})
class DeleteCart(APIView):
    def post(self, request):
        id = request.data.get('id')
        CartModel.objects.filter(cname_id=id).delete()
        return Response({"message":"删除成功"})
class ChangeAll(APIView):
    def put(self, request):
        select = request.data.get('select')
        user = request.data.get('user')
        CartModel.objects.filter(user=user).update(select=select)
        return Response({"message":"修改成功"})

